package com.caigp.cookbook2.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.caigp.cookbook2.R;
import com.caigp.cookbook2.base.BaseActivity;
import com.caigp.cookbook2.bean.CookBook;
import com.caigp.cookbook2.fragment.ListFragment;
import com.caigp.cookbook2.util.AppUtil;
import com.caigp.cookbook2.util.AssetsUtil;
import com.caigp.cookbook2.util.HttpClient;
import com.caigp.cookbook2.util.JsonUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SearchListActivity extends BaseActivity {

    private static final String TAG = SearchListActivity.class.getSimpleName();

    @BindView(R.id.search_think_recycler_view)
    RecyclerView thinkRecyclerView;

    private ListFragment listFragment;

    private int start = 0;

    private List<String> thinkNameList = new ArrayList<>();

    private BaseQuickAdapter<String, BaseViewHolder> adapter;

    /**
     * 要搜索的名称
     */
    private String name = "";

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String result = (String) msg.obj;
                    JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();
                    int status = jsonObject.get("status").getAsInt();
                    if (status == 0) {
                        JsonObject resultJsonObject = jsonObject.get("result").getAsJsonObject();
                        JsonArray jsonArray = resultJsonObject.getAsJsonArray("list");
                        List<CookBook> cookBookList = JsonUtil.getList(jsonArray.toString(), CookBook.class);
                        listFragment.setCookBookList(cookBookList);
                    } else if (status == 205) {
                        //没有信息
                        listFragment.setLoadEnd();
                    }
                    break;
                case 1:
                    start -= 10;
                    listFragment.setLoadMoreFail();
                    break;
            }
        }
    };
    private SearchView searchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_list);
        ButterKnife.bind(this);
        initThinkRecyclerView();
        getName();
        listFragment = (ListFragment) getSupportFragmentManager().findFragmentById(R.id.list_fragment);
        listFragment.setRecyclerViewListener(new ListFragment.RecyclerViewListener() {
            @Override
            public void scrollToTop() {

            }

            @Override
            public void scrollToBottom() {
                start += 10;
                requestData();
            }
        });
    }

    private void getName() {
        name = getIntent().getStringExtra("name");
    }

    @Override
    protected boolean showHomeAsUp() {
        return true;
    }


    private void initThinkRecyclerView() {
        LinearLayoutManager llm = new LinearLayoutManager(this);
        adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_menu, thinkNameList) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, String item) {
                helper.setText(R.id.text_view, item);
            }
        };
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String query = thinkNameList.get(position);
                searchView.setQuery(query, true);
                searchView.clearFocus();
            }
        });
        thinkRecyclerView.setLayoutManager(llm);
        thinkRecyclerView.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
        searchView.setQueryHint("搜索食材、菜谱");
        searchView.setIconified(false);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                //Log.d(TAG, "onQueryTextSubmit: " + query);
                setActionBarTitle(query);
                name = query;
                listFragment.clearCookBookList();
                requestData();
                thinkNameList.clear();
                adapter.notifyDataSetChanged();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //Log.d(TAG, "onQueryTextChange: " + newText);
                thinkNameList.clear();
                if (!newText.isEmpty()) {
                    for (String s : cookNameList) {
                        if (s.contains(newText)) {
                            thinkNameList.add(s);
                        }
                    }
                }
                adapter.notifyDataSetChanged();
                return false;
            }
        });

        if (name != null && !name.isEmpty()) {
            searchView.setQuery(name, true);
            searchView.clearFocus();
        }
        return super.onCreateOptionsMenu(menu);
    }

    private void requestData() {
        RequestBody requestBody = new FormBody.Builder()
                .add("keyword", name)
                .add("start", String.valueOf(start))
                .add("appkey", AppUtil.appkey)
                .build();
        HttpClient.sendPost(AppUtil.search, requestBody, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                handler.sendEmptyMessage(1);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                int code = response.code();
                if (code == 200) {
                    String body = response.body().string();
                    //Log.d(TAG, "onResponse: " + body);
                    Message message = handler.obtainMessage();
                    message.obj = body;
                    message.what = 0;
                    handler.sendMessage(message);
                }
            }
        });
    }
}
